/**
 * 
 * @class UserFormPanel
 * @extends Ext.FormPanel
 * @description 用于窗口的信息编辑管理
 */
UserFormPanel = Ext.extend(Ext.FormPanel, {
	constructor : function(conf) {
		Ext.applyIf(this, conf);
		this.userId = this.userId ? this.userId : '';
		this.initUI();
		UserFormPanel.superclass.constructor.call(this, {
					id : 'UserFormPanel_' + this.userId,
					iconCls : 'add-user',
					title : (this.username ? this.username : '') + '人员信息',
					autoScroll : true,
					width : 900,
					tbar : [{
								text : '保存',
								iconCls : 'btn-save',
								scope : this,
								handler : this.save
							}, '-'

					],
					layout : 'hbox',
					items : [this.depTreePanel, {
						layout : 'vbox',
						width : 500,
						height : 880,
						items : [this.depGridPanel, this.requiredPanel, this.rolePanel]
					}]
				});

		if (this.userId != '') {
			this.requiredPanel.loadData({
						url : __ctxPath + '/system/loadAppUser.do?userId=' + this.userId,
						root : 'data',
						preName : 'appUser',
						scope : this,
						success : function(resp, options) {
							var photo = this.getCmpByName('appUser.photo').getValue();
							if (photo != '' && photo != null) {
								this.photoPanel.body.update('<img src="'
										+ __ctxPath + '/attachFiles/' + photo
										+ '"  width="100%" height="100%"/>');
							}
						}
					});
			this.getDockedItems('toolbar[dock="top"]')[0].insert(2, {
						text : '重设密码',
						iconCls : 'btn-password',
						scope : this,
						handler : function() {
							new setPasswordForm(this.userId);
						}
					});
		}
	},
	// ==================functions start===============
	/**
	 * 上传图片
	 */
	uploadPhoto : function() {
		var dialog = App.createUploadDialog({
			file_cat : 'system/appUser',
			scope : this,
			callback : function(data) {
				var photo = this.requiredPanel.getCmpByName('appUser.photo');
				if(data.length != 0) {
					photo.setValue(data[0].filePath);
					this.photoPanel.body.update('<img src="' + __ctxPath
							+ '/attachFiles/' + data[0].filePath
							+ '"  width="100%" height="100%"/>');
				}
			},
			permitted_extensions : ['jpg', 'png', 'bmp', 'gif']
		}).show();
	},

	/**
	 * 选择Title时，进行图片切换
	 * 
	 * @param {} combo
	 * @param {} record
	 * @param {} index
	 */
	selectedTitle : function(combo, record, index) {
		if (combo.value == '0') {
			this.photoPanel.body.update('<img src="' + __ctxPath
					+ '/images/default_image_female.jpg"/>');
		} else {
			this.photoPanel.body.update('<img src="' + __ctxPath
					+ '/images/default_image_male.jpg"/>');
		}
	},
	// ==================function end==================

	// 初始化UI
	initUI : function() {
		this.photoPanel = new Ext.Panel({
					tbar : [{
								text : '上传',
								iconCls : 'btn-upload',
								scope : this,
								handler : this.uploadPhoto
							}],
					title : '个人照片',
					width : 230,
					height : 380,
					html : '<img src="' + __ctxPath
							+ '/images/default_image_male.jpg"/>'
				});

		this.requiredPanel = new Ext.Panel({
					title : '基本信息',
					width : 498,
					height : 400,
					layout : 'form',
					bodyStyle : 'padding:6px',
					defaults : {
						xtype: 'textfield',
						anchor : '98%,98%'
					},
					items : [{
								xtype : 'hiddenfield',
								name : 'appUser.userId'
							}, {
								fieldLabel : '登录账号',
								name : 'appUser.username',
								allowBlank : false
							}, {
								fieldLabel : '真实姓名',
								name : 'appUser.fullname',
								allowBlank : false
							}, {
								fieldLabel : '用户类型',
								xtype : 'combo',
								name : 'appUser.roleType',
								queryMode : 'local',
								editable : false,
								triggerAction : 'all',
								store : [['1','院领导'],['2','教师'],['3','班主任'],['9','教辅人员']],
								value : '3',
								allowBlank : false
							}, {
								fieldLabel : '性别',
								xtype : 'combo',
								name : 'appUser.title',
								queryMode : 'local',
								editable : false,
								triggerAction : 'all',
								store : [['1', '男'], ['0', '女']],
								value : '1',
								listeners : {
									scope : this,
									'select' : this.selectedTitle
								}
							}, {
								fieldLabel : '是否可用',
								name : 'appUser.status',
								xtype : 'combo',
								queryMode : 'local',
								editable : false,
								triggerAction : 'all',
								store : [['1', '激活'], ['0', '禁用']],
								value : 1
							}, {
								fieldLabel : '联系电话',
								name : 'appUser.phone'
							}, {
								fieldLabel : '家庭住址',
								name : 'appUser.address'
							},
							 {
								fieldLabel : '所属教研室',
								name : 'appUser.jiaoyanshi'
							},
							 {
								fieldLabel : '职称',
								name : 'appUser.zhicheng'
							},{
								xtype : 'hiddenfield',
								name : 'appUser.photo'
							}, {
								fieldLabel : '序号',
								xtype : 'numberfield',
								name : 'appUser.userSn'
							}]
				});

		if (this.userId == '') {
			this.requiredPanel.insert(2, new Ext.form.TextField({
								fieldLabel : '登录密码',
								name : 'appUser.password',
								inputType : 'password',
								allowBlank : false
							}));
			this.requiredPanel.doLayout();
		}

		// 可选择的单位树
		this.depTreePanel = Ext.create('Ext.ux.TreePanelEditor', {
					title : '单位',
					url : __ctxPath + '/system/treeDepartment.do?demId=1',// 1代表行政维度
					scope : this,
					autoScroll : true,
					showContextMenu : false,
					height : 880,
					width : 350,
					dblclick : this.depTreePanelDblClick
				});

		this.depGridPanel = new KE.GridPanel({
					clicksToEdit : 1,
					isShowTbar : false,
					showPaging : false,
					title : '已选单位',
					width : '100%',
					height : 150,
					// 通过后台返回值
					url : __ctxPath + '/system/findUserOrg.do',
					baseParams: {
						userId: this.userId,
						orgId: this.orgId
					},
					fields : ['userOrgId', 'orgId', 'orgName', 'isPrimary', 'isCharge'],
					selType: 'cellmodel', 
					plugins: [
						Ext.create('Ext.grid.plugin.CellEditing',{  
                     		clicksToEdit:1 //设置单击单元格编辑  
                 		})],
					columns : [{
								header : '单位名',
								dataIndex : 'orgName'
							}, {
								header : '是否主单位',
								dataIndex : 'isPrimary',
								renderer : function(val) {
									return val == 1 ? '是' : '否';
								},
								editor : {
									id : 'orgPrimary',
									xtype : 'combo',
									mode : 'local',
									editable : false,
									triggerAction : 'all',
									store : [['1', '是'], ['0', '否']],
									value : 0,
									listeners : {
										scope : this,
										'select' : this.setPrimary
									}
								}
							}, {
								header : '是否分管单位',
								dataIndex : 'isCharge',
								renderer : function(val) {
									return val == 1 ? '是' : '否';
								},
								editor : {
									id : 'orgCharge',
									xtype : 'combo',
									mode : 'local',
									editable : false,
									triggerAction : 'all',
									store : [['1', '是'], ['0', '否']],
									value : 0,
									listeners : {
										scope : this,
										'select' : this.setCharge
									}
								}
							}],
					listeners : {
						scope : this,
						'rowdblclick' : this.depGridPanelDblClick
					}
				});

		// 单位选择Panel
		this.depPanel = new KE.HBoxPanel({
					items : [this.depTreePanel, this.depGridPanel]
				});

		this.roleForSelPanel = new KE.GridPanel({
					width : 248,
					height : 550,
					isShowTbar : false,
					showPaging : false,
					autoScroll : true,
					title : '可选角色(双击选择)',
					url : __ctxPath + '/system/getRolesAppUser.do?userId='
							+ this.userId,
					fields : ['roleId', 'roleName'],
					columns : [{
								header : '角色名',
								dataIndex : 'roleName'
							}],
					listeners : {
						scope : this,
						'rowdblclick' : this.roleForSelPanelDblClick
					}
				});

		this.roleSelectedPanel = new KE.GridPanel({
					width : 248,
					height : 550,
					isShowTbar : false,
					showPaging : false,
					autoScroll : true,
					title : '已选角色(双击删除)',
					url : __ctxPath + '/system/getSelRolesAppUser.do?userId='
							+ this.userId,
					fields : ['roleId', 'roleName'],
					columns : [{
								header : '角色名',
								dataIndex : 'roleName'
							}],
					listeners : {
						scope : this,
						'rowdblclick' : this.roleSelectedPanelDblClick
					}
				});
		// 角色选择Panel
		this.rolePanel = new KE.HBoxPanel({
					width : 498,
					height : 550,
					items : [this.roleForSelPanel, this.roleSelectedPanel]
				});

		// 创建基本信息的FieldSet
		this.basePanel = new KE.HBoxPanel({
					items : [this.photoPanel, this.requiredPanel]
				});

	},

	// 删除已选择的角色
	roleSelectedPanelDblClick : function(grid, record) {
		if (this.userId != '') {
			var roleId = record.data.roleId;
			Ext.Ajax.request({
						url : __ctxPath + '/system/delRoleAppUser.do?userId=' + this.userId,
						params : {
							roleId : roleId
						},
						method : 'POST',
						scope : this,
						success : function(response, options) {
							Ext.ux.Toast.msg('操作', '成功删除角色！');
							this.roleSelectedPanel.getStore().remove(record);
						}
					});
		} else {
			this.roleSelectedPanel.getStore().remove(record);
		}
	},

	// 删除已选单位数据
	depGridPanelDblClick : function(grid, record) {
		var data = record.data;
		if (data.userOrgId && data.isPrimary != 1) {
			Ext.Ajax.request({
						url : __ctxPath + '/system/delUserOrg.do?userOrgId='
								+ data.userOrgId,
						method : 'Post',
						scope : this,
						success : function(response, options) {
							Ext.ux.Toast.msg('操作信息', '成功删除所属单位');
							this.depGridPanel.getStore().remove(record);
						}
					});
		} else {
			if (data.isPrimary != 1) {
				this.depGridPanel.getStore().remove(record);
			} else {
				Ext.ux.Toast.msg('操作信息', '主单位不能删除');
			}
		}
	},
	// 角色选择器单击
	roleForSelPanelDblClick : function(grid, record) {
		var store = grid.getStore();
		var selStore = this.roleSelectedPanel.getStore();
		for (var i = 0; i < selStore.getCount(); i++) {
			if (selStore.getAt(i).data.roleId == record.data.roleId) {
				break;
			}
		}
		var rec = selStore.getModel().create(record.data);
		selStore.insert(selStore.getCount(), rec);
	},
	// 设置为主单位
	setPrimary : function(combo, record, index) {

		var primaryFlag = false;
		var selRe = this.depGridPanel.getSelectionModel().getSelection();
		var store = this.depGridPanel.getStore();
		var index;
		for (var i = 0; i < store.getCount(); i++) {
			var data = store.getAt(i).data;
			if (data.isPrimary == 1 && data.orgId != selRe[0].data.orgId) {
				primaryFlag = true;
				break;
			}
		}
		if (primaryFlag && combo.value == 1) {
			Ext.getCmp('orgPrimary').setValue(0);
			Ext.ux.Toast.msg('操作信息', '只能有一个主岗位');
			primaryFlag = false;
			return;
		}
	},
	//设置分管领导
	setCharge: function(combo, record, index) {
		var selRe = this.depGridPanel.getSelectionModel().getSelections();
		if(selRe[0].data.isPrimary==1 && combo.value==1) {
			Ext.getCmp('orgCharge').setValue(0);
			Ext.ux.Toast.msg('操作信息', '主单位时，不能同时为分管单位！');
		}
	},
	// 单位树的双击
	depTreePanelDblClick : function(view, node) {
		if (node.data.id == 0)
			return;
		// 检查该nodeid是否已经存在于depGrid用户
		var store = this.depGridPanel.getStore();
		var nodeId = node.data.id;
		for (var i = 0; i < store.getCount(); i++) {
			if (store.getAt(i).data.orgId == nodeId) {
				return;
			}
		}
		var rec = store.getModel().create({
					orgId : node.id,
					orgName : node.data.text,
					isPrimary : store.getCount() > 0 ? 0 : 1
		});
		store.insert(store.getCount(), rec);
	},
	// 保存
	save : function() {
		// 取得选择的角色
		var roleIds = '';
		// 取得选择的单位
		var orgIds = [];
		
		for (var i = 0; i < this.roleSelectedPanel.getStore().getCount(); i++) {
			if (i > 0)
				roleIds += ',';
			roleIds += this.roleSelectedPanel.getStore().getAt(i).data.roleId;
		}

		var primaryOrgFlag = false;
		for (var i = 0; i < this.depGridPanel.getStore().getCount(); i++) {
			var data = this.depGridPanel.getStore().getAt(i).data
			orgIds.push(data);
			if (data.isPrimary == 1) {
				primaryOrgFlag = true;
			}
		}
		if (orgIds.length == 0 || !primaryOrgFlag) {
			Ext.ux.Toast.msg('操作信息', '必须选择一个主单位');
			return;
		}


		if (primaryOrgFlag) {
			$postForm({
						url : __ctxPath + '/system/saveOrUpdateAppUser.do',
						formPanel : this,
						params : {
							roleIds : roleIds,
							orgIds : Ext.encode(orgIds)
						},
						scope : this,
						callback : function(fp, action) {
							if (action.result.success == true) {
								App.getContentPanel().remove(this, true);
								if(Ext.getCmp('AppUserGrid')) {
									Ext.getCmp('AppUserGrid').getStore().reload();
								}
							} else {
								Ext.ux.Toast.msg('操作信息', action.result.msg);
							}
						}
					});
		}
	}
});